extends Node2D
@onready var trace: Line2D = $Trace
@onready var try_count_show: Label = $CanvasLayer/VBoxContainer/HBoxContainer/TryCountShow
@onready var result_show: Panel = $CanvasLayer/ResultShow

const BASE_GRID = preload("res://grid/base_grid.tscn")
const BASE_PLAYER = preload("res://player/base_player.tscn")
const SYNC_PLAYER = preload("res://player/sync_player.tscn")

var base_grid : BaseGrid
var player : Player
var sync_player : SyncPlayer
var move_pos_trace : Array
var disable_input : bool
var is_need_back : bool #是否需要主从相反行动
var on_trace : bool
var try_count : int = GlobelFileRw.try_count
func _ready() -> void:
	base_grid = BASE_GRID.instantiate()
	base_grid.on_trace_log.connect(_on_trace_log_event)
	result_show.hide()
	_load_level_data()
	add_child(base_grid)
	_init_player()
	_init_sync_player()

func _init_player() -> void :
	player = BASE_PLAYER.instantiate()
	var cell = base_grid._get_only_cell_by_type(GlobelEnum.CellType.PlayerStart)
	player.global_position = cell.global_position
	player.current_index = cell.get_index()
	get_tree().current_scene.call_deferred("add_child",player)

func _init_sync_player() -> void :
	sync_player = SYNC_PLAYER.instantiate()
	var cell = base_grid._get_only_cell_by_type(GlobelEnum.CellType.DupStart,-1)
	sync_player.global_position = cell.global_position
	sync_player.current_index = cell.get_index()
	get_tree().current_scene.call_deferred("add_child",sync_player)

#func _unhandled_key_input(_event: InputEvent) -> void:
	#if disable_input : return
	#var right = Input.get_axis("ui_left","ui_right")
	#var up = Input.get_axis("ui_up","ui_down")
	#if right != 0.0 or up != 0.0:
		#var move_dir = Vector2(right,up)
		#var _is_pass = player._move_to(move_dir,base_grid)
		#sync_player._move_to((move_dir*-1) if is_need_back else move_dir)
		#_check_pass()

func _process(_delta: float) -> void:
	try_count_show.text = str(try_count)

func _load_level_data() -> void :
	var data = GlobelFileRw._read_file(GlobelFileRw._get_next_level())
	var grid_xy = data.grid_xy
	var cells = data.cells
	is_need_back = data.get("is_need_back",false)
	base_grid.grid_xy = grid_xy
	base_grid.cells = cells

func _check_pass() -> bool :
	var current_player_cell = base_grid.get_child(player.current_index)
	var current_sync_player_cell = base_grid.get_child(sync_player.current_index)
	if is_same(current_player_cell.type,GlobelEnum.CellType.hit) or is_same(current_sync_player_cell.type,GlobelEnum.CellType.hit) :
		disable_input = true
		GlobelFileRw.is_pass_reload = false
		get_tree().call_deferred("reload_current_scene")
		return true
	if is_same(current_player_cell.type,GlobelEnum.CellType.PlayerEnd) and is_same(current_sync_player_cell.type,GlobelEnum.CellType.DupEnd) :
		disable_input = true
		print("通关")
		get_tree().call_deferred("reload_current_scene")
		return true
	if is_same(current_player_cell.type,GlobelEnum.CellType.Back) :
		is_need_back = true
	return false

func _input(event: InputEvent) -> void:
	if event as InputEventMouseButton :
		if disable_input : return
		on_trace = event.is_pressed()
		if not on_trace :
			if move_pos_trace.size() > 1 :
				disable_input = true
				if await _auto_move() : return
				try_count -= 1
				if try_count == 0 :
					print("------------->失败需看广告，或重新来")
					result_show.on_failed.emit()

func _on_trace_log_event(cell : BaseCell, is_check : bool) -> void :
	if disable_input : return
	if on_trace :
		if is_check :
			var current_player_cell = base_grid.get_child(player.current_index)
			if not current_player_cell == cell : return
		if move_pos_trace.is_empty() and cell._check_hovered() : return
		if move_pos_trace :
			var back_item = move_pos_trace.back()
			if base_grid._get_target_dir(back_item,cell) == Vector2.ZERO : return
		move_pos_trace.append(cell)
		trace.add_point(cell.global_position)
		print(move_pos_trace)

func _auto_move() -> bool :
	var is_pass : bool
	var first = move_pos_trace.pop_front()
	var second = move_pos_trace.pop_front()
	while second :
		var move_dir = base_grid._get_target_dir(first,second)
		var wait_time = 0.3
		var player_next_cell = player._get_next_cell(move_dir)
		var sync_player_next_cell = sync_player._get_next_cell(move_dir)
		if not player_next_cell == sync_player_next_cell :
			player._move_to(move_dir,base_grid,wait_time)
			sync_player._move_to((move_dir*-1) if is_need_back else move_dir,wait_time)
			await get_tree().create_timer(wait_time).timeout
		is_pass = _check_pass()
		if is_pass : break
		first = second
		second = move_pos_trace.pop_front()
	trace.clear_points()
	disable_input = false
	move_pos_trace.clear()
	return is_pass
